package com.qriver.distributedlock.controller;

import com.qriver.distributedlock.service.DistributedLockService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    private Logger logger = LoggerFactory.getLogger(DemoController.class);

    @Autowired
    private DistributedLockService distributedLockService;

    @RequestMapping("mysqlLock")
    @Transactional(rollbackFor = Exception.class)
    public String testLock() throws Exception {
        logger.debug("进入testLock()方法;");
        if(distributedLockService.tryLock("order")){
            logger.debug("获取到分布式锁；");
            Thread.sleep(30 * 1000);
        }else{
            logger.debug("获取分布式锁失败；");
            throw new Exception("获取分布式锁失败；");
        }
        logger.debug("执行完成；");
        return "返回结果";
    }

}
